import { Article, Channel } from '@/types/data'
import { HomeAction } from '@/types/store'
type HomeType = {
  userChannel: Channel[]
  allChannel: Channel[]
  active: number
  articleList: {
    [key: number]: {
      timestamp: number
      articles: Article[]
    }
  }
}
const initValue: HomeType = {
  userChannel: [],
  allChannel: [],
  active: 0,
  articleList: {},
}

export default function home(state = initValue, action: HomeAction): HomeType {
  if (action.type === 'home/getUserChannel') {
    return { ...state, userChannel: action.payload }
  }
  if (action.type === 'home/getAllChannels') {
    return {
      ...state,
      allChannel: action.payload,
    }
  }
  if (action.type === 'home/changeActive') {
    return { ...state, active: action.payload }
  }
  if (action.type === 'home/getArticle') {
    const { channel_id, timestamp, articles } = action.payload
    const old = state.articleList[channel_id]?.articles ?? []
    return {
      ...state,
      articleList: {
        ...state.articleList,
        [channel_id]: {
          timestamp: +timestamp,
          articles: [...old, ...articles],
        },
      },
    }
  }
  if (action.type === 'home/getNewArticle') {
    const { channel_id, timestamp, articles } = action.payload
    // const old = state.articleList[channel_id]?.articles
    return {
      ...state,
      articleList: {
        ...state.articleList,
        [channel_id]: {
          timestamp: +timestamp,
          articles: [...articles],
        },
      },
    }
  }
  return state
}
